package com.lr.springbootdemo.custom;

import com.lr.springbootdemo.bean.Constants;
import com.lr.springbootdemo.bean.Result;
import com.lr.springbootdemo.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * .统一异常拦截
 * Created by li.rui on 2016-06-13.
 */
public class CustomExceptionHandler implements HandlerExceptionResolver{
    private static Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        ModelAndView mv = new ModelAndView();
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Result result = new Result();
        if (e instanceof EmptyResultDataAccessException){//如果是因为没有查询到数据异常
            logger.warn(e.getMessage());
            result.setMsg("没有数据");
        }else if (e instanceof CustomException){
            logger.warn(e.getMessage());
            result.setMsg("请求失败:"+e.getMessage());
            result.setStatus(Constants.ERROR);
        }else{
            logger.error(e.getMessage(),e);
            result.setMsg("请求失败");
            result.setStatus(Constants.ERROR);
        }
        view.setAttributesMap(JsonUtil.string2Object(JsonUtil.object2String(result),Map.class));
        mv.setView(view);
        return mv;
    }
}
